package com.lzx.adx.report.hander;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.UUID;
import com.alipay.api.AlipayApiException;
import com.blueggy.scrape.AbstractScrapeMessageHandler;
import com.blueggy.scrape.ScrapeCourier;
import com.blueggy.scrape.ScrapeMessage;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.SpringContextUtils;
import com.lzx.adx.report.biz.HwWphBiz;
import com.lzx.adx.report.dto.WphOrderDTO;
import com.lzx.adx.report.model.wph.OrderListResp;
import com.lzx.adx.report.model.wph.OrderResponse;
import com.lzx.adx.report.model.wph.WphRequest;
import com.lzx.adx.report.service.WphOrderService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@ChannelHandler.Sharable
@Slf4j
public class ScrapeHander extends AbstractScrapeMessageHandler {


    @Resource
    private HwWphBiz hwWphBiz;

    @Override
    protected void channelRead(ChannelHandlerContext ctx, ScrapeMessage msg) {

        log.info("收到消息： {}", msg);

        String data = msg.getData();
        WphRequest wphRequest = JsonUtils.parseObject(data, WphRequest.class);

        OrderListResp orderListResp = wphRequest.getOrderListResp();
        OrderResponse orderResponse = orderListResp.getData();
        List<WphOrderDTO> list = orderResponse.getData();

        if(CollectionUtil.isNotEmpty(list)){
            //存储订单信息
            for (WphOrderDTO wphOrderDTO : list) {
                MDC.put("report.requestNo", UUID.fastUUID().toString());
                //
                WphOrderService wphOrderService = SpringContextUtils.getBean(WphOrderService.class);
                wphOrderDTO.setCreateTime(new Date());
                wphOrderDTO.setUpdateTime(new Date());
                wphOrderService.saveData(wphOrderDTO);

                HwWphBiz hwWphBiz = SpringContextUtils.getBean(HwWphBiz.class);
                //hwWphBiz
                try {
                    hwWphBiz.callBackUrl(wphOrderDTO);
                } catch (AlipayApiException e) {
                    throw new RuntimeException(e);
                }
            }
        }else{
            log.info("当前没有订单");
        }
        ScrapeCourier.instance().reply(msg.getClientId(), msg.getSequence(), "OK");
    }
}